import time
import RPi.GPIO as GPIO

# 设置GPIO模式为BCM模式
GPIO.setmode(GPIO.BCM)

# 定义RGB LED的红、绿、蓝三个引脚
RED_PIN = 21
GREEN_PIN = 20
BLUE_PIN = 22

# 设置RGB LED的三个引脚为输出模式
GPIO.setup(RED_PIN, GPIO.OUT)
GPIO.setup(GREEN_PIN, GPIO.OUT)
GPIO.setup(BLUE_PIN, GPIO.OUT)

# 创建三个PWM输出实例
red_pwm = GPIO.PWM(RED_PIN, 500)
green_pwm = GPIO.PWM(GREEN_PIN, 500)
blue_pwm = GPIO.PWM(BLUE_PIN, 500)

# 启动PWM输出
red_pwm.start(0)
green_pwm.start(0)
blue_pwm.start(0)

# 定义渐变函数
def fade(color, start, end, step):
    for i in range(start, end, step):
        color.ChangeDutyCycle(i)
        time.sleep(0.02)
    for i in range(end, start, -step):
        color.ChangeDutyCycle(i)
        time.sleep(0.02)

# 循环播放渐变灯效果
while True:
    fade(red_pwm, 0, 100, 2)
    fade(green_pwm, 0, 100, 2)
    fade(blue_pwm, 0, 100, 2)
